package com.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.order.bean.Foods;
import com.order.bean.Order;
import com.order.bean.OrderDetail;
import com.order.bean.User;
import com.order.common.entiry.ResultCode;
import com.order.common.exception.CommonException;
import com.order.common.util.SqlSessionFactoryUtil;
import com.order.mapper.OrderDetailMapper;
import com.order.mapper.OrderMapper;
import com.order.service.OrderService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.math.BigDecimal;
import java.util.List;

public class OrderServiceImpl implements OrderService {

    private OrderMapper orderMapper;

    private OrderDetailMapper orderDetailMapper;

    private SqlSession sqlSession;

    private void closeMapper() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    private void initMapper() {
        SqlSessionFactory factory = SqlSessionFactoryUtil.getInstace();
        SqlSession sqlSession = factory.openSession(true);
        orderMapper = sqlSession.getMapper(OrderMapper.class);
        orderDetailMapper = sqlSession.getMapper(OrderDetailMapper.class);
    }

    @Override
    public int batchInsertDetail(List<OrderDetail> orderDetails) {
        initMapper();
        int count = orderDetailMapper.batchInsert(orderDetails);
        closeMapper();
        return count;
    }

    @Override
    public Order updateOrder(Order order) {
        initMapper();
        orderMapper.update(order);
        return order;
    }

    @Override
    public Order getUserNewOrder(Order order) {
        initMapper();
        Order dbOrder = orderMapper.getUserLatestOrder(order);
        closeMapper();
        return dbOrder;
    }

    @Override
    public Order checkOutOrder(Order order) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        initMapper();
        List<OrderDetail> orderDetails = orderDetailMapper.queryAll(orderDetail);
        if (orderDetails.size() > 0) {
            double totalPrice = 0;
            Integer sum = 0;
            for (OrderDetail item : orderDetails) {
                totalPrice += (item.getPrice() * item.getNum());
                sum += item.getNum();
            }
            order.setTotalPrice(BigDecimal.valueOf(totalPrice));
            order.setFoodNum(sum);
            orderMapper.update(order);
        } else {
            new CommonException(ResultCode.NO_ORDER_INFO);
        }
        return order;
    }

    @Override
    public PageInfo<Foods> selectPage(Integer userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        initMapper();
        List<Foods> foods = orderMapper.selectOrderAll(userId);
        closeMapper();
        return PageInfo.of(foods);
    }
}
